package com.rj.framework.component.tech.mybatis;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.rj.framework.component.TechnicalComponent;
import com.rj.framework.context.Context;
import com.rj.util.SpringUtils;

/**
 * 数据操作组件
 */
public class DatabaseComponent implements TechnicalComponent<DataBaseRequest<?>, DataBaseResponse, Context<?>> {
    @Override
    public DataBaseResponse execute(DataBaseRequest<?> request, Context<?> context) {
        BaseMapper baseMapMapper = SpringUtils.getBean(request.getMapperClass());
        Object entity = request.getReqEntity();
        Wrapper<?> wrapper = request.getWrapper();
        switch (request.getOperationType()) {
            case FIND_ONE:
                return new DataBaseResponse<>(baseMapMapper.selectOne(wrapper), true);
            case CREATE:
                return new DataBaseResponse<>(entity, baseMapMapper.insert(entity) > 0);
            case UPDATE:
                return new DataBaseResponse<>(entity, baseMapMapper.update(entity, wrapper) > 0);
            case DELETE:
                return new DataBaseResponse<>(entity, baseMapMapper.delete(wrapper) > 0);
            case FIND_PAGE:
                return new DataBaseResponse<>(baseMapMapper.selectPage(request.getPage(), wrapper), true);
            case FIND_ALL:
                return new DataBaseResponse<>(baseMapMapper.selectList(wrapper), true);
            default:
                throw new TechnicalException("DatabaseComponent", "Unsupported operation type: " + request.getOperationType());
        }
    }
}